package terra.model.object.action;

import terra.Config;
import terra.model.object.GameObject;
import terra.model.object.NpcObject;
import terra.model.object.ai.AbstractAI;
import terra.model.object.interfaces.Attackable;

public class ActionFollow extends AbstractAction {

	private static final long serialVersionUID = 6728633910541554326L;
	public boolean allowJump = true;
	public boolean moveLeft = false;
	public boolean forAttack = true;
	public GameObject target;
	int maxTime = 10000;

	public ActionFollow(AbstractAI ai, GameObject targ) {
		super(AbstractAI.ACTION_MOVE, ai);
		target = targ;
	}

	public ActionFollow(AbstractAI ai, Attackable target2, boolean canJump) {
		super(AbstractAI.ACTION_MOVE, ai);
		target = (GameObject) target2;
		allowJump = canJump;
	}

	@Override
	public void update(int delta) {
		maxTime -= delta;
		float diffX;
		int distance = (int) target.distanceTo(ai.getOwner());
		if (target.getX() < ai.getOwner().getX())
			ai.getOwner().setLeft(true);
		else
			ai.getOwner().setLeft(false);

		if (ai.getOwner().isLeft())
			diffX = -ai.getOwner().getStat().getMoveSpeed() / 1000f * delta;
		else
			diffX = ai.getOwner().getStat().getMoveSpeed() / 1000f * delta;

		if (!ai.getOwner().isCollision2(ai.getOwner().getX() + diffX,
				ai.getOwner().getY()))
			ai.getOwner().setX(ai.getOwner().getX() + diffX);
		else if (allowJump)
			ai.getOwner().setYacceleration(-ai.getOwner().getJumpStartSpeed());
		else
			end();
		if (forAttack
				&& distance < ((NpcObject) (ai.getOwner())).getAttackRange())
			end();
		if (!forAttack && distance < Config.tileSize / 2)
			end();
		if (maxTime <= 0)
			end();

	}

}
